from flask import Flask, render_template, request, session, jsonify
from sudoku import Sudoku

app = Flask(__name__)
app.secret_key = 'secure_secret_key_123'

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/new-game', methods=['POST'])
def new_game():
    data = request.get_json()
    try:
        sudoku = Sudoku(difficulty=data.get('difficulty', 'medium'))
        session['sudoku'] = {
            'solution': sudoku.solution,
            'puzzle': sudoku.puzzle,
            'user_input': sudoku.user_input
        }
        return jsonify(puzzle=sudoku.puzzle)
    except Exception as e:
        return jsonify(error=str(e)), 500

@app.route('/validate', methods=['POST'])
def validate():
    sudoku_data = session.get('sudoku')
    if not sudoku_data:
        return jsonify(error="Game not initialized"), 400
    
    sudoku = Sudoku()
    sudoku.solution = sudoku_data['solution']
    sudoku.puzzle = sudoku_data['puzzle']
    sudoku.user_input = request.json['userInput']
    
    session['sudoku']['user_input'] = sudoku.user_input
    return jsonify(valid=sudoku.validate(), remaining=sudoku.remaining_empty)

@app.route('/hint')
def get_hint():
    sudoku_data = session.get('sudoku')
    if not sudoku_data:
        return jsonify(error="Game not initialized"), 400
    
    sudoku = Sudoku()
    sudoku.solution = sudoku_data['solution']
    sudoku.puzzle = sudoku_data['puzzle']
    sudoku.user_input = sudoku_data['user_input']
    
    hint = sudoku.hint()
    return jsonify(hint=hint if not hint else {
        'row': hint[0],
        'col': hint[1],
        'value': hint[2]
    })

@app.route('/get-current-game')
def get_current_game():
    sudoku_data = session.get('sudoku')
    if not sudoku_data:
        return jsonify(error="Game not initialized"), 400
    return jsonify(solution=sudoku_data['solution'])

@app.route('/check-cell', methods=['POST'])
def check_cell():
    data = request.json
    sudoku_data = session.get('sudoku')
    
    if not sudoku_data:
        return jsonify(error="Game not initialized"), 400
    
    row = data['row']
    col = data['col']
    value = data['value']
    
    is_correct = sudoku_data['solution'][row][col] == value
    return jsonify(correct=is_correct)

if __name__ == '__main__':
    app.run(debug=True)